<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="2" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="最终发布"/>
    </el-steps>

    <el-form label-width="120px">
      <el-button type="text" @click="toAddChapterDialog">添加章节</el-button>
      <!-- 章节 -->
      <ul class="chapterList">
        <li
          v-for="chapter in chapterNestedList"
          :key="chapter.id">
          <p>
            {{ chapter.title }}
            <span class="acts">
              <el-button type="text" @click="toAddVideoDialog(chapter.id)">添加课时</el-button>
              <el-button type="text" @click="toUpdateChapterDialog(chapter)">编辑</el-button>
              <el-button type="text" @click="toDeleteChapter(chapter.id)">删除</el-button>
            </span>
          </p>
          <!-- 视频 -->
          <ul class="chapterList videoList">
            <li
              v-for="video in chapter.children"
              :key="video.id">
              <p>{{ video.title }}
                <span class="acts">
                  <el-button type="text" @click="toUpdateVideoDialog(video)">编辑</el-button>
                  <el-button type="text" @click="toDeleteVideo(video.id)">删除</el-button>
                </span>
              </p>
            </li>
          </ul>
        </li>
      </ul>
      <div>
        <el-button @click="previous">上一步</el-button>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">下一步</el-button>
      </div>
    </el-form>

    <!--章节对应的弹框-->
    <el-dialog :visible.sync="isShowChapter" title="添加章节">
      <el-form :model="chapter" label-width="120px">
        <el-form-item label="章节标题">
          <el-input v-model="chapter.title"></el-input>
        </el-form-item>
        <el-form-item label="章节排序">
          <el-input-number :min="0" controls-position="right" v-model="chapter.sort"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowChapter = false">取消</el-button>
        <el-button @click="saveOrUpdateChapter" type="primary">确定</el-button>
      </div>
    </el-dialog>

    <!--小节对应的弹框-->
    <el-dialog :visible.sync="isShowVideo" title="添加小节">
      <el-form :model="video" label-width="120px">
        <el-form-item label="课时标题">
          <el-input v-model="video.title"/>
        </el-form-item>
        <el-form-item label="课时排序">
          <el-input-number v-model="video.sort" :min="0" controls-position="right"/>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio-group v-model="video.isFree">
            <el-radio :label="true">免费</el-radio>
            <el-radio :label="false">默认</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            :on-success="handleVodUploadSuccess"
            :on-remove="handleVodRemove"
            :before-remove="beforeVodRemove"
            :on-exceed="handleUploadExceed"
            :file-list="fileList"
            :action="BASE_API+'/eduvod/vod'"
            :limit="1"
            class="upload-demo">
            <el-button size="small" type="primary">上传视频</el-button>
            <el-tooltip placement="right-end">
              <div slot="content">最大支持1G，<br>
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br>
                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、MP4、<br>
                MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB、<br>
                SWF、TS、VOB、WMV、WEBM 等视频格式上传</div>
              <i class="el-icon-question"/>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowVideo = false">取消</el-button>
        <el-button @click="saveOrUpdateVideo" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

  import chapter from '@/api/edu/chapter';
  import video from '@/api/edu/video';

  export default {
    data() {
      return {
        isShowChapter: false,
        isShowVideo: false,
        courseId: '',
        currentChapterId: '', // 当前进行新增操作时，存放其章节id
        saveBtnDisabled: false, // 保存按钮是否禁用,
        fileList: [],
        BASE_API: process.env.BASE_API,
        chapterNestedList: [],
        chapter: {
          title: '',
          sort: 0
        },
        video: {
          title: '',
          sort: '',
          isFree: false,
          videoSourceId: '', // 视频上传后的id
          videoOriginalName: ''
        }
      }
    },

    created() {
      this.init();
    },

    methods: {
      /**
       * 上一步
       */
      previous() {
        this.$router.push({ path: '/course/info/' + this.courseId })
      },
      /**
       * 下一步
       */
      next() {
        this.$router.push({ path: '/course/publish/' + this.courseId })
      },
      /**
       * 页面初始化时调用的方法
       */
      init() {
        // 1.获取courseId
        if (!this.$route.params.id) {
          this.$router.push("/course/info");
        }
        this.courseId = this.$route.params.id;
        // 2.查询章节数据
        chapter.getChapterVideo(this.courseId).then(res => {
          this.chapterNestedList = res.data.list;
        })
      },
      /**
       * 保存或更新章节
       */
      saveOrUpdateChapter() {
        if (this.chapter.id) {
          // 1.更新操作
          this.chapter.courseId = this.courseId;
          chapter.updateChapter(this.chapter).then(res => {
            if (res.success) {
              this.$message.success("更新成功");
              this.isShowChapter = false;
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        } else {
          // 2.新增操作
          this.chapter.courseId = this.courseId;
          chapter.addChapter(this.chapter).then(res => {
            if (res.success) {
              this.$message.success("更新成功");
              this.isShowChapter = false;
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        }
      },
      /**
       * 新增章节时打开对话框的方法
       */
      toAddChapterDialog() {

        this.chapter = {
          title: '',
          sort: ''
        }
        this.isShowChapter = true;
      },
      /**
       * 更新章节时打开对话框的方法
       * @param chapterInfo
       */
      toUpdateChapterDialog(chapterInfo) {
        chapter.getChapterInfo(chapterInfo.id).then(res => {
          this.chapter = res.data.chapter;
        });
        this.isShowChapter = true;
      },
      /**
       * 删除章节
       * @param id
       */
      toDeleteChapter(id) {
        this.$confirm('是否要删除，一旦执行不能撤销！', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          chapter.deleteChapter(id).then(res => {
            if (res.success) {
              this.$message.success("删除章节成功");
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        })
      },
      /**
       * 新增或修改小节
       */
      saveOrUpdateVideo() {
        if (this.video.id) {
          // 更新操作
          video.updateVideo(this.video).then(res => {
            if (res.success) {
              this.$message.success("更新小节成功");
              this.isShowVideo = false;
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        } else {
          // 新增操作
          this.video.courseId = this.courseId;
          this.video.chapterId = this.currentChapterId;

          video.addVideo(this.video).then(res => {
            if (res.success) {
              this.$message.success("新增小节成功");
              this.isShowVideo = false;
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        }
      },
      /**
       * 新增小节时打开对话框的方法
       * @param chapterId 新增的小节属于哪个章节
       */
      toAddVideoDialog(chapterId) {
        this.video = {
          title: '',
          sort: '',
          isFree: '',
          videoSourceId: '',
          videoOriginalName: ''
        }
        this.currentChapterId = chapterId;
        this.isShowVideo = true;
      },
      /**
       * 更新小节时打开对话框的方法
       * @param video
       */
      toUpdateVideoDialog(videoInfo) {
        video.getVideoInfo(videoInfo.id).then(res => {
          this.video = res.data.video;
          this.fileList = [{'name': this.video.videoOriginalName}]
        })
        this.isShowVideo = true;
      },
      /**
       * 删除小节
       * @param videoId
       */
      toDeleteVideo(videoId) {
        this.$confirm('是否要删除本小节，一旦删除无法恢复', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          video.deleteVideo(videoId).then(res => {
            if (res.success) {
              this.$message.success("删除小节成功");
              this.init();
            } else {
              this.$message.error(res.message);
            }
          })
        })
      },
      /**
       * 视频上传成功后的回调
       */
      handleVodUploadSuccess(res, file, fileList) {
        // 将返回值中的videoId赋值给页面中对应的变量
        this.video.videoSourceId = res.data.videoId;
        this.video.videoOriginalName = file.name;
        // 将文件名称赋值给对应属性
        this.video.videoOriginalName = file.name;
      },
      /**
       * 视频从fileList中被移除时的回调（即点击确认框中的确定调用的方法）
       */
      handleVodRemove(file, fileList) {
        video.deleteAliyunVod(this.video.videoSourceId).then(res => {
          if (res.success) {
            this.$message.success("删除视频成功");
            // 清空文件列表
            this.fileList = [];
            // 将对应字段清空
            this.video.videoSourceId = '';
            this.video.videoOriginalName = '';
          } else {
            this.$message.error(res.message);
          }
        })
      },
      /**
       * 视频从fileList中被移除之前的回调（即点击×时调用的方法）
       * 一般都是显示一个确认框
       */
      beforeVodRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      },
      /**
       * fileList中文件的数量超过limit时发生的回调
       */
      handleUploadExceed(files, fileList) {
        this.$message.warning("想要重新上传视频，请先删除已上传的视频")
      }
    }
  }
</script>

<style scoped>
  .chapterList{
    position: relative;
    list-style: none;
    margin: 0;
    padding: 0;
  }
  .chapterList li{
    position: relative;
  }
  .chapterList p{
    float: left;
    font-size: 20px;
    margin: 10px 0;
    padding: 10px;
    height: 70px;
    line-height: 50px;
    width: 100%;
    border: 1px solid #DDD;
  }
  .chapterList .acts {
    float: right;
    font-size: 14px;
  }

  .videoList{
    padding-left: 50px;
  }
  .videoList p{
    float: left;
    font-size: 14px;
    margin: 10px 0;
    padding: 10px;
    height: 50px;
    line-height: 30px;
    width: 100%;
    border: 1px dotted #DDD;
  }
</style>
